<!-- ERP 产品的新增/修改 -->
<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="70%">
    <el-form
      ref="formRef"
      label-position="top"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row :gutter="5">

        <el-col :span="5">
          <el-form-item label="业务" prop="categoryId">
            <el-tree-select
              v-model="formData.categoryId"
              :data="categoryList"
              :props="defaultProps"
              check-strictly
              @change="handleCategoryChange"
              default-expand-all
              placeholder="请选择业务"
              class="w-1/1"
            />
          </el-form-item>
        </el-col>

        <el-col :span="7">
          <el-form-item label="工厂编号" prop="factoryNumber">
            <el-input v-model="formData.factoryNumber" placeholder="请输入工厂编号"/>
          </el-form-item>
        </el-col>

        <el-col :span="9">
          <el-form-item label="产品名称(工厂名称)" prop="factoryName">
            <el-input v-model="formData.factoryName" placeholder="请输入名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="false">
          <el-form-item label="条码" prop="barCode">
            <el-input v-model="formData.barCode" placeholder="请输入条码"/>
          </el-form-item>
        </el-col>

        <el-col :span="3">
          <el-form-item label="单位" prop="unitId">
            <el-select v-model="formData.unitId" clearable placeholder="请选择单位" class="w-1/1">
              <el-option
                v-for="unit in unitList"
                :key="unit.id"
                :label="unit.name"
                :value="unit.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-row :gutter="10" v-if="showGlass">
          <el-col :span="8">
            <el-form-item label="VIN" prop="vin" label-width="80">
              <el-input
                class="!w-230px"
                v-model="formData.vin"
                style="max-width: 600px"
                placeholder="请输入VIN"
              >
                <template #append>
                  <el-button @click="handleJyCarTypeByVin" type="success">搜索车型</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="车型" prop="carType">
              <el-input v-model="formData.carType" placeholder="请输入车型"/>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="部位" prop="businessType">
              <el-select v-model="formData.businessType"
                         @change="handleSaleTypeChange"
                         placeholder="请选择部位" clearable>
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.ERP_SALE_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="原厂零件(OE)" prop="oe">
              <el-input v-model="formData.oe" placeholder="请输入原厂零件"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-col :span="5">
          <el-form-item label="品牌" prop="brandId">
            <el-tree-select
              v-model="formData.brandId"
              :data="changeBrandListByCategoryId"
              :props="defaultProps"
              check-strictly
              default-expand-all
              placeholder="请选择品牌"
              class="w-1/1"
            />
          </el-form-item>
        </el-col>


        <el-col :span="6">
          <el-form-item label="规格" prop="standard">
            <el-input v-model="formData.standard" placeholder="请输入规格"/>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入备注"/>
          </el-form-item>
        </el-col>

        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="销售价" prop="salePrice">
              <el-input v-model="formData.salePrice" placeholder="请输入销售价"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="渠道价" prop="channelPrice">
              <el-input v-model="formData.channelPrice" placeholder="请输入渠道价"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="保险价" prop="insurancePrice">
              <el-input v-model="formData.insurancePrice" placeholder="请输入保险价"/>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio
                  v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                  :key="dict.value"
                  :label="dict.value"
                >
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="4S店价" prop="flagshipPrice">
              <el-input v-model="formData.flagshipPrice" placeholder="请输入4S店价"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="综修厂价格" prop="repairFactoryPrice">
              <el-input v-model="formData.repairFactoryPrice" placeholder="请输入综修厂价格"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="零售价" prop="retailPrice">
              <el-input v-model="formData.retailPrice" placeholder="请输入零售价"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工时价" prop="manHourPrice">
              <el-input v-model="formData.manHourPrice" placeholder="请输入工时价"/>
            </el-form-item>
          </el-col>


          <el-col :span="6">
            <el-form-item label="玻璃工时价" prop="glassAndManHourPrice">
              <el-input v-model="formData.glassAndManHourPrice" placeholder="请输入玻璃工时价"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="加工尺寸" prop="finishSize">
              <el-input v-model="formData.finishSize" placeholder="请输入加工尺寸"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="自定义名称" prop="customName">
              <el-input v-model="formData.customName" placeholder="请输入自定义名称"/>
            </el-form-item>
          </el-col>
        </el-row>

      </el-row>

      <el-row>
        <el-col :span="6">
          <el-form-item label="夹层" prop="interlayerStatus">
            <el-switch
              v-model="formData.interlayerStatus"
              size="large"
              active-text="有"
              inactive-text="无"
            />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="共享" prop="shareStatus">
            <el-switch
              v-model="formData.shareStatus"
              size="large"
              active-text="共享"
              inactive-text="不共享"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="图片信息" prop="imgUrl">
            <UploadImgs :disabled="isDetail" v-model="formData.imgUrl"/>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {ProductApi, ProductVO} from '@/api/erp/product/product'
import {ProductCategoryApi, ProductCategoryVO} from '@/api/erp/product/category'
import {ProductBrandApi, ProductBrandVO} from '@/api/erp/product/brand'
import {ProductUnitApi, ProductUnitVO} from '@/api/erp/product/unit'
import {CommonStatusEnum} from '@/utils/constants'
import {defaultProps, handleTree} from '@/utils/tree'
import {DICT_TYPE, getIntDictOptions, getStrDictOptions} from '@/utils/dict'
import {ElLoading, ElMessage} from "element-plus";
import {SaleOrderApi} from "@/api/erp/sale/order";

/** ERP 产品 表单 */
defineOptions({name: 'ProductForm'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const showGlass = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  barCode: '-',
  categoryId: undefined,
  unitId: undefined,
  status: undefined,
  standard: undefined,
  remark: undefined,
  vin: undefined,
  carType: undefined,
  expiryDay: undefined,
  weight: undefined,
  purchasePrice: undefined,
  salePrice: undefined,
  channelPrice: undefined,
  insurancePrice: undefined,
  minPrice: undefined,

  brandId: undefined,
  factoryNumber: undefined,
  oe: undefined,
  amMainBrandName: undefined,
  amBrandName: undefined,
  amSeriesName: undefined,
  amVehicleName: undefined,
  amYear: undefined,
  businessType: undefined,
  imgUrl: undefined,

  flagshipPrice: undefined,
  repairFactoryPrice: undefined,
  retailPrice: undefined,
  manHourPrice: undefined,
  glassAndManHourPrice: undefined,
  finishSize: undefined,
  customName: undefined,
  interlayerStatus: false,
  shareStatus: false
})
const formRules = reactive({
  name: [{required: true, message: '产品名称不能为空', trigger: 'blur'}],
  // barCode: [{required: true, message: '产品条码不能为空', trigger: 'blur'}],
  businessType: [{required: true, message: '请选择业务类型', trigger: 'blur'}],
  categoryId: [{required: true, message: '产品分类编号不能为空', trigger: 'blur'}],
  brandId: [{required: true, message: '请选择产品品牌', trigger: 'blur'}],
  unitId: [{required: true, message: '单位编号不能为空', trigger: 'blur'}],
  status: [{required: true, message: '产品状态不能为空', trigger: 'blur'}]
})
const formRef = ref() // 表单 Ref
const categoryList = ref<ProductCategoryVO[]>([]) // 产品分类列表
const brandList = ref<ProductBrandVO[]>([]) // 产品分类列表
const changeBrandListByCategoryId = ref<ProductBrandVO[]>([]) // 产品分类列表
const unitList = ref<ProductUnitVO[]>([]) // 产品单位列表

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ProductApi.getProduct(id)
    } finally {
      formLoading.value = false
    }
  }

  formData.value.shareStatus = formData.value.shareStatus == 1 || formData.value.shareStatus == null ? false : true;
  formData.value.interlayerStatus = formData.value.interlayerStatus == 1 || formData.value.interlayerStatus == null ? false : true;

  // 产品分类
  const categoryData = await ProductCategoryApi.getProductCategorySimpleList()
  categoryList.value = handleTree(categoryData, 'id', 'parentId')

  const brandData = await ProductBrandApi.getProductBrandSimpleList()
  brandList.value = handleTree(brandData, 'id', 'parentId')
  changeBrandListByCategoryId.value = brandList.value;
  // 产品单位
  unitList.value = await ProductUnitApi.getProductUnitSimpleList()

  //formData.value.categoryId 对应名称 categoryData 查询对应名称
  let name = categoryList.value.find(item => item.id == formData.value.categoryId)?.name;

  if (name == undefined) {
    showGlass.value = false;
  } else if (name == '玻璃') {
    showGlass.value = true;
  } else {
    showGlass.value = false;
  }

}
defineExpose({open, formData}) // 提供 open 方法，用于打开弹窗


/**
 * 销售类型
 * @param e
 */
const handleSaleTypeChange = async (e) => {
  let cateName = categoryList.value.find(item => item.id == formData.value.categoryId)?.name;
  console.log(cateName)
  //获取部位名称
  let name = getIntDictOptions(DICT_TYPE.ERP_SALE_TYPE).find(item => item.value == e)?.label;
  if (name == undefined) {
    ElMessage.error('查询OE异常');
    return;
  }
  if (cateName == '玻璃') {
    const amVehicleId = formData.value.amVehicleId;
    if (amVehicleId != undefined && amVehicleId.length > 0) {

      const loading = ElLoading.service({
        lock: true,
        text: 'OE码查询中...',
        background: 'rgba(0, 0, 0, 0.7)',
      })

      const data = await SaleOrderApi.getStdPartNameByAmVehicleId(formData.value.amVehicleId, name, formData.value.vin);
      if (data == null) {
        ElMessage.error('未查询OE码信息');
      } else {
        formData.value.oe = data.oe;
      }

      setTimeout(() => {
        loading.close()
      }, 500)
    }
  }
}

//根据vin获取车型
const handleJyCarTypeByVin = async () => {
  const vinVal = formData.value.vin;
  if (vinVal == undefined || vinVal.length != 17) {
    ElMessage.error('请输入正确的17位VIN');
    return;
  }

  const loading = ElLoading.service({
    lock: true,
    text: '车型查询中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  const data = await SaleOrderApi.getJyCarTypeByVin(vinVal);


  if (data == null) {
    formData.value.carType = undefined;
    formData.value.productType = undefined;
    formData.value.amVehicleId = undefined;
    formData.value.amMainBrandName = undefined;
    formData.value.amBrandName = undefined;
    formData.value.amSeriesName = undefined;
    formData.value.amSeriesId = undefined;
    formData.value.amVehicleName = undefined;
    ElMessage.error('未查询到车型信息,请检查VIN是否正确');
  } else {
    //车型
    formData.value.carType = data.amBrandName + data.amSeriesName + data.amVehicleName;

    formData.value.amVehicleId = data.amVehicleId;
    formData.value.amMainBrandName = data.amMainBrandName;
    formData.value.amBrandName = data.amBrandName;
    formData.value.amSeriesName = data.amSeriesName;
    formData.value.amSeriesId = data.amSeriesId;
    formData.value.amVehicleName = data.amVehicleName;
    formData.value.amYear = data.amYear;
  }
  setTimeout(() => {
    loading.close()
  }, 500)
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true


  if (formData.value.factoryName != undefined && formData.value.factoryName.length > 0) {
    formData.value.name = formData.value.factoryName;
  } else {
    formData.value.name = formData.value.carType;
  }

  formData.value.shareStatus = formData.value.shareStatus == false ? 1 : 2;
  formData.value.interlayerStatus = formData.value.interlayerStatus == false ? 1 : 2;

  try {
    const data = formData.value as unknown as ProductVO
    if (formType.value === 'create') {
      await ProductApi.createProduct(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProductApi.updateProduct(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const handleCategoryChange = (value: number) => {
  changeBrandListByCategoryId.value = brandList.value;
  const category = categoryList.value.find((item) => item.id === value);
  let brandIds = category.brandIds;
  //brandList查找匹配的品牌
  changeBrandListByCategoryId.value = brandList.value.filter((item) => brandIds.includes(item.id));

  //选择是否是玻璃
  if (category.name === '玻璃') {
    showGlass.value = true;
  } else {
    showGlass.value = false;
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    barCode: '-',
    categoryId: undefined,
    unitId: undefined,
    status: CommonStatusEnum.ENABLE,
    standard: undefined,
    remark: undefined,
    expiryDay: undefined,
    carType: undefined,
    vin: undefined,
    weight: undefined,
    purchasePrice: undefined,
    salePrice: undefined,
    channelPrice: undefined,
    insurancePrice: undefined,
    minPrice: undefined,

    brandId: undefined,
    factoryNumber: undefined,
    oe: undefined,
    amMainBrandName: undefined,
    amBrandName: undefined,
    amSeriesName: undefined,
    amVehicleName: undefined,
    amVehicleId: undefined,
    amYear: undefined,
    businessType: undefined,
    imgUrl: undefined,


    flagshipPrice: undefined,
    repairFactoryPrice: undefined,
    retailPrice: undefined,
    manHourPrice: undefined,
    glassAndManHourPrice: undefined,
    finishSize: undefined,
    customName: undefined,
    interlayerStatus: false,
    shareStatus: false
  }
  formRef.value?.resetFields()
}
</script>
